package com.zhf.servlet;

import com.zhf.entity.User;
import com.zhf.service.UserService;
import com.zhf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.queryUserByUserNameAndPassword(userName, password);
        if(user == null){
            request.setAttribute("loginError", "用户名或密码错误！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        else{
            request.getSession().setAttribute("user", user);
            // 实现7天内免登录
            // 创建cookie对象用于存放用户信息
            Cookie userNameCookie = new Cookie("userName", userName);
            // 设置 cookie 一周内有效， 一小时 3600 秒， 一天24小时， 一周7天
            userNameCookie.setMaxAge(3600 * 24 * 7);
            response.addCookie(userNameCookie);
            response.sendRedirect("index.do");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
